package cn.com.csg.smartenergy.listener;

import cn.com.csg.smartenergy.mqtt.DeviceOfflineHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

/**
 * 监听 Redis key的过期事件
 * @author ysguo
 */
@Slf4j
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    private DeviceOfflineHandler offlineHandler;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * 针对redis key 失效事件，进行数据处理
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 用户做自己的业务处理即可,注意message.toString()可以获取失效的key
        String expiredKey = message.toString();
        try {
            this.offlineHandler.handleOnlineMessage(expiredKey);
        } catch (Exception e) {
            log.error(String.format("处理 Redis key 失效数据出现异常：expiredKey: %s", expiredKey), e);
        }
    }
}
